<template>
    <div>
        <h1>{{ groupDetailsData.find(item => item.label === 'Organization Name')?.value }}</h1>
        <p>{{ groupDetailsData.find(item => item.label === 'Description')?.value }}</p>

        <a-row justify="center">
            <a-col :span="10" style="margin-top: 24px;">
                <a-list :size="medium" :bordered="false" :split="false">
                    <template #header>
                        Preferred VPS Providers
                    </template>
                    <template #default>
                        <a-list-item v-for="provider in groupDetailsData.find(item => item.label === 'VPS Providers')?.value || []" :key="provider">
                            {{ provider }}
                        </a-list-item>
                    </template>
                </a-list>
            </a-col>
        </a-row>
        <div v-if="groupDetailsData.length > 0">
            <a-row justify="center" :gutter="24">
                <a-col :span="10">
                    <a-list :size="medium" :bordered="false" :pagination-props="domainPaginationProps" :split="false">
                        <template #header>
                            Used Domains
                        </template>
                        <template #default>
                            <a-list-item v-for="domain in groupDetailsData.find(item => item.label === 'Domains')?.value || []" :key="domain">
                                {{ domain }}
                            </a-list-item>
                        </template>
                    </a-list>
                </a-col>
                <a-col :span="10">
                    <a-list :size="medium" :bordered="false" :pagination-props="ipPaginationProps" :split="false">
                        <template #header>
                            Used IPs
                        </template>
                        <template #default>
                            <a-list-item v-for="ip in groupDetailsData.find(item => item.label === 'IPs')?.value || []" :key="ip">
                                {{ ip }}
                            </a-list-item>
                        </template>
                    </a-list>
                </a-col>
            </a-row>
            <!-- 引入 domainipcount 组件并传递数据 -->
            <DomainIpCount :domainCount="domainPaginationProps.total" :ipCount="ipPaginationProps.total" />
        </div>
    </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';
import { Network, DataSet } from 'vis-network/standalone/esm/vis-network';
// 步骤 1：导入组件
import DomainIpCount from './domainipcount.vue';

export default {
    components: {
        DomainIpCount
    },
    setup() {
        const route = useRoute();
        const groupDetailsData = ref([]);
        const selectedNode = ref(null);
        const medium = 'medium';
        const domainPaginationProps = reactive({
            defaultPageSize: 10,
            total: 0
        });
        const ipPaginationProps = reactive({
            defaultPageSize: 10,
            total: 0
        });

        const fetchGroupDetails = async () => {
            try {
                const id = route.params.id;
                const response = await axios.get(`http://localhost:3001/api/apt-groups/${id}`);
                const groupDetails = response.data;

                groupDetailsData.value = [
                    { label: 'Organization Name', value: groupDetails.organization },
                    { label: 'Description', value: groupDetails.introduction },
                    { label: 'Domains', value: groupDetails.domains },
                    { label: 'IPs', value: groupDetails.ips },
                    { label: 'VPS Providers', value: groupDetails.vpsProviders }
                ];

                domainPaginationProps.total = groupDetails.domains?.length || 0;
                ipPaginationProps.total = groupDetails.ips?.length || 0;

                const graphResponse = await axios.get(`http://localhost:3001/api/apt-groups/${groupDetails.organization}/neo4j-graph`);
                drawGraph(graphResponse.data.nodes, graphResponse.data.links, groupDetails);
            } catch (error) {
                console.error('请求后端失败:', error);
            }
        };

        const drawGraph = (nodesData, linksData, groupDetails) => {
            console.log('linksData:', linksData); // 添加日志
            console.log('linksData:', nodesData); // 添加日志
            const container = document.getElementById('network');

            const styledNodes = nodesData.map(node => {
                let color = '#97C2FC'; // 默认色
                let shape = 'ellipse'; // 默认形状为圆形
                let fontColor = '#E5EAF3'; // 浅色字体

                if (node.type === 'organization') {
                    color = '#FFD700';  // 金色
                    shape = 'star';     // 星形
                    node.introduction = groupDetails.introduction;
                    node.id = groupDetails.id;
                } else if (node.type === 'Domain') {
                    color = '#FFA07A';  // 橙色
                    shape = 'ellipse';  // 圆形
                } else if (node.type === 'IP') {
                    color = '#90EE90';  // 绿色
                    shape = 'ellipse';  // 圆形
                }

                return {
                    ...node,
                    shape,
                    color,
                    font: { color: fontColor, size: 14, face: 'Arial' },
                    fixed: { x: false, y: false }
                };
            });

            const nodes = new DataSet(styledNodes);

            const styledEdges = linksData.map(edge => ({
               ...edge,
                color: { color: 'white' }, // 浅灰线条
                width: 1.5
            }));
            const edges = new DataSet(styledEdges);

            const data = { nodes, edges };

            const options = {
                layout: { improvedLayout: true },
                interaction: { hover: true, tooltipDelay: 100 },
                physics: { stabilization: false }
            };

            const network = new Network(container, data, options);

            network.on('click', params => {
                if (params.nodes.length > 0) {
                    const nodeId = params.nodes[0];
                    selectedNode.value = nodes.get(nodeId);
                }
            });

            network.on('dragEnd', params => {
                if (params.nodes.length > 0) {
                    params.nodes.forEach(id => {
                        const pos = network.getPositions([id])[id];
                        nodes.update({
                            id,
                            fixed: { x: true, y: true },
                            x: pos.x,
                            y: pos.y
                        });
                    });
                }
            });
        };

        onMounted(() => {
            fetchGroupDetails();
        });

        return {
            groupDetailsData,
            selectedNode,
            domainPaginationProps,
            ipPaginationProps,
            medium
        };
    }
};
</script>

<style scoped>
:deep(.arco-list-header) {
    background-color: #76797b;
}
:deep(.arco-list) {
    color: white;
}
</style>